<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="商品名"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <Dict v-model="queryParams.category" code="prod_category" />
        </el-form-item>
        <el-form-item label="用途" prop="usageType">
          <Dict v-model="queryParams.usageType" code="prod_usage_type" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon><Search /></template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon><Refresh /></template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button v-hasPerm="['mrt:mrt-product:add']" type="success" @click="handleOpenDialog()">
          <template #icon><Plus /></template>
          新增
        </el-button>
        <el-button
          v-hasPerm="['mrt:mrt-product:delete']"
          type="danger"
          :disabled="removeIds.length === 0"
          @click="handleDelete()"
        >
          <template #icon><Delete /></template>
          删除
        </el-button>
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="pageData"
        :row-key="(row) => row.id + row.updateTime"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column key="name" label="商品名称" prop="name" min-width="150" align="center" />
        <!--        <el-table-column-->
        <!--          key="slug"-->
        <!--          label="商品seo地址"-->
        <!--          prop="slug"-->
        <!--          min-width="150"-->
        <!--          align="center"-->
        <!--        />-->
        <el-table-column label="商品分类" width="150" align="center">
          <template #default="scope">
            <DictLabel v-model="scope.row.category" code="prod_category" />
          </template>
        </el-table-column>
        <el-table-column label="用途" width="150" align="center">
          <template #default="scope">
            <DictLabel v-model="scope.row.usageType" code="prod_usage_type" />
          </template>
        </el-table-column>
        <!--        <el-table-column key="brand" label="品牌名称" prop="brand" min-width="150" align="center" />-->
        <!--        <el-table-column key="stock" label="库存数量" prop="stock" min-width="150" align="center" />-->
        <!--        <el-table-column key="sku" label="库存编码 SKU" prop="sku" min-width="150" align="center" />-->
        <el-table-column key="images" label="主图" prop="images" min-width="150" align="center">
          <template #default="scope">
            <ImageDisplay :images="scope.row.thumbnail" height="30px" />
          </template>
        </el-table-column>
        <!--        <el-table-column key="images" label="商品图片" prop="images" min-width="150" align="center">-->
        <!--          <template #default="scope">-->
        <!--            <ImageDisplay :images="scope.row.images" height="30px" />-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column key="price" label="当前价格" prop="price" min-width="150" align="center" />
        <el-table-column
          key="originalPrice"
          label="原价"
          prop="originalPrice"
          min-width="150"
          align="center"
        />
        <el-table-column key="tags" label="标签" prop="tags" min-width="150" align="center" />
        <!--        <el-table-column-->
        <!--          key="weight"-->
        <!--          label="重量（kg）"-->
        <!--          prop="weight"-->
        <!--          min-width="150"-->
        <!--          align="center"-->
        <!--        />-->
        <el-table-column
          key="dimensions"
          label="尺寸(cm)"
          prop="dimensions"
          min-width="150"
          align="center"
        />
        <el-table-column label="状态" width="150" align="center">
          <template #default="scope">
            <DictLabel v-model="scope.row.status" code="prod_status" />
          </template>
        </el-table-column>
        <el-table-column
          key="salesCount"
          label="销量"
          prop="salesCount"
          min-width="150"
          align="center"
        />
        <!--        <el-table-column-->
        <!--          key="rating"-->
        <!--          label="平均评分"-->
        <!--          prop="rating"-->
        <!--          min-width="150"-->
        <!--          align="center"-->
        <!--        />-->
        <!-- <el-table-column
          key="metaTitle"
          label="SEO标题"
          prop="metaTitle"
          min-width="150"
          align="center"
        /> -->
        <!--        <el-table-column-->
        <!--          key="metaDescription"-->
        <!--          label="SEO描述"-->
        <!--          prop="metaDescription"-->
        <!--          min-width="150"-->
        <!--          align="center"-->
        <!--        />-->
        <el-table-column key="regin" label="地区" prop="regin" min-width="150" align="center" />
        <el-table-column
          key="createTime"
          label="创建时间"
          prop="createTime"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="updateTime"
          label="更新时间"
          prop="updateTime"
          min-width="150"
          align="center"
        />
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
              v-hasPerm="['mrt:mrt-product:edit']"
              type="primary"
              size="small"
              link
              @click="handleOpenDialog(scope.row.id)"
            >
              <template #icon><Edit /></template>
              编辑
            </el-button>
            <el-button
              v-hasPerm="['mrt:mrt-product:delete']"
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            >
              <template #icon><Delete /></template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery()"
      />
    </el-card>

    <!-- 商品表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="800px"
      class="form-dialog"
      @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="formData.name" placeholder="商品名称" />
        </el-form-item>

        <el-form-item label="别名(唯一)" prop="slug">
          <el-input
            v-model="formData.slug"
            placeholder="商品别名（URL标识，每个商品唯一，不可以重复）"
            @input="handleSlugInput"
          />
        </el-form-item>

        <el-form-item label="商品分类" prop="category">
          <dict v-model="formData.category" code="prod_category" />
        </el-form-item>

        <el-form-item label="用途" prop="usageType">
          <dict v-model="formData.usageType" code="prod_usage_type" />
        </el-form-item>

        <!--        <el-form-item label="品牌名称" prop="brand">-->
        <!--          <el-input v-model="formData.brand" placeholder="品牌名称" />-->
        <!--        </el-form-item>-->

        <el-form-item label="当前价格" prop="price">
          <el-input-number v-model="formData.price" placeholder="当前价格" />
        </el-form-item>

        <el-form-item label="原价" prop="originalPrice">
          <el-input-number v-model="formData.originalPrice" placeholder="原价（划线价）" />
        </el-form-item>

        <!--        <el-form-item label="库存数量" prop="stock">-->
        <!--          <el-input-number v-model="formData.stock" placeholder="库存数量" />-->
        <!--        </el-form-item>-->

        <!--        <el-form-item label="库存编码 SKU" prop="sku">-->
        <!--          <el-input v-model="formData.sku" placeholder="库存编码 SKU" />-->
        <!--        </el-form-item>-->

        <el-form-item v-if="dialog.visible" label="商品详情大图" prop="topImage">
          <DetailImageUpload v-model="formData.topImage" />
        </el-form-item>

        <el-form-item v-if="dialog.visible" label="主图" prop="thumbnail">
          <SingleImageUpload v-model="formData.thumbnail" />
        </el-form-item>

        <el-form-item v-if="dialog.visible" label="商品图片" prop="images">
          <MultiImageUpload v-model="formData.images" :limit="9" />
        </el-form-item>

        <el-form-item v-if="dialog.visible" label="商品视频" prop="videos">
          <MultiImageUpload
            v-model="formData.videos"
            type="video"
            accept="video/*"
            :maxFileSize="150"
            :limit="3"
          />
        </el-form-item>

        <el-form-item v-if="dialog.visible" label="商品描述" prop="description">
          <WangEditor v-model="formData.description" height="400px" />
        </el-form-item>

        <el-form-item label="标签" prop="tags">
          <el-input v-model="formData.tags" placeholder="标签（英文逗号分隔）" />
        </el-form-item>

        <!--        <el-form-item label="重量（kg）" prop="weight">-->
        <!--          <el-input-number v-model="formData.weight" placeholder="重量（kg）" />-->
        <!--        </el-form-item>-->

        <el-form-item label="尺寸" prop="dimensions">
          <el-input v-model="formData.dimensions" placeholder="尺寸（长x宽x高，单位cm）" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <dict v-model="formData.status" code="prod_status" />
        </el-form-item>

        <el-form-item label="销量" prop="salesCount">
          <el-input-number v-model="formData.salesCount" placeholder="销量" />
        </el-form-item>

        <!--        <el-form-item label="平均评分" prop="rating">-->
        <!--          <el-input-number v-model="formData.rating" placeholder="平均评分" />-->
        <!--        </el-form-item>-->

        <!-- <el-form-item label="SEO标题" prop="metaTitle">
          <el-input v-model="formData.metaTitle" type="textarea" placeholder="SEO标题" />
        </el-form-item>

        <el-form-item label="SEO描述" prop="metaDescription">
          <el-input v-model="formData.metaDescription" type="textarea" placeholder="SEO描述" />
        </el-form-item> -->

        <el-form-item label="地区" prop="regin">
          <el-input v-model="formData.regin" type="textarea" placeholder="多个使用英文逗号分隔" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import SingleImageUpload from "@/components/Upload/SingleImageUpload.vue";
import DetailImageUpload from "@/components/Upload/DetailImageUpload.vue";
defineOptions({
  name: "MrtProduct",
  inheritAttrs: false,
});

import MrtProductAPI from "@/api/mrt/mrt-product.js";
import MultiImageUpload from "@/components/Upload/MultiImageUpload.vue";
import WangEditor from "@/components/WangEditor/index.vue";

const queryFormRef = ref();
const dataFormRef = ref();

const loading = ref(false);
const removeIds = ref([]);
const total = ref(0);

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  keywords: "",
});

// 商品表格数据
const pageData = ref([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 商品表单数据
const formData = reactive({ salesCount: 1000000, status: 1 });

// 商品表单校验规则
const rules = reactive({
  name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
  slug: [{ required: true, message: "请输入商品别名", trigger: "blur" }],
  category: [{ required: true, message: "请输入商品分类", trigger: "blur" }],
  usageType: [{ required: true, message: "请输入用途", trigger: "blur" }],
  thumbnail: [{ required: true, message: "请选择主图", trigger: "blur" }],
  images: [{ required: true, message: "请选择商品图片", trigger: "blur" }],
  description: [{ required: true, message: "请输入商品描述", trigger: "blur" }],
});

/** 查询商品 */
function handleQuery() {
  loading.value = true;
  MrtProductAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置商品查询 */
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection) {
  removeIds.value = selection.map((item) => item.id);
}

/** 打开商品弹窗 */
function handleOpenDialog(id) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改商品";
    MrtProductAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增商品";
  }
}

/** 提交商品表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        MrtProductAPI.update(id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        MrtProductAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭商品弹窗 */
function handleCloseDialog() {
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = undefined;
  formData.topImage = undefined;
  formData.salesCount = 1000000;
  formData.status = 1;
  dialog.visible = false;
}

/** 处理别名输入，只允许字母、数字、连字符和下划线 */
function handleSlugInput(value) {
  // 移除空格和特殊字符，只保留字母、数字、连字符和下划线
  const cleanValue = value.replace(/[^a-zA-Z0-9\-_]/g, "");
  formData.slug = cleanValue;
}

/** 删除商品 */
function handleDelete(id) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      MrtProductAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

onMounted(() => {
  handleQuery();
});
</script>
